package org.linlinjava.litemall.wx.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.redis.RedisCache;
import org.linlinjava.litemall.core.system.SystemConfig;
import org.linlinjava.litemall.core.util.JsonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallSchool;
import org.linlinjava.litemall.db.service.LitemallSchoolService;
import org.linlinjava.litemall.wx.service.GetRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学校
 */
@RestController
@RequestMapping("/wx/school")
@Validated
public class WxSchoolController extends GetRegionService {
	private final Log logger = LogFactory.getLog(WxSchoolController.class);

	@Autowired
	private LitemallSchoolService schoolService;
	@Autowired
	private RedisCache redisCache;

	@GetMapping("list")
	public Object list(String schoolName, @RequestParam(defaultValue = "1") Integer page,
			@RequestParam(defaultValue = "10") Integer limit) {
		
		String cacheKey = "schoolData";
		if (redisCache.hasData(cacheKey)) {
			String json = redisCache.getCacheObject(cacheKey);
			return ResponseUtil.ok(JsonUtil.jsonToObject(json));
		}
		List<LitemallSchool> SchoolList = schoolService.querySelective(schoolName, page, limit);
		Map<String, Object> entity = new HashMap<>();
		entity.put("list", SchoolList);
		redisCache.setCacheObject(cacheKey, JsonUtil.mapToJson(entity));
		return ResponseUtil.ok(entity);
	}

	@GetMapping("get_lng_lat")
	public Object get_lng_lat(String lng,String lat) {
		List<LitemallSchool> schoolList =  schoolService.get_lng_lat(lat,lng,1,10);
		/*
		for(int i=0;i<schoolList.size();i++) {
			Double m = Double.valueOf(schoolList.get(i).getDistance());
			if(m < 1) {
				m=m*1000;
				schoolList.get(i).setDistance(m+"m");
			}else {
				schoolList.get(i).setDistance(m+"Km");
			}
		}*/
		Boolean type = false;
		if(schoolList.size() > 0) {
			Double mm = Double.valueOf(schoolList.get(0).getDistance());
			if(mm > SystemConfig.getlongitudeANDlatitude()) {//默认大于100公里
				type = true;
			}
		}
		 Map<String, Object> entity = new HashMap<>();
		 entity.put("schoolList", schoolList);
		 entity.put("schoolType", type);
		 
		return ResponseUtil.ok(entity);
	}
	
	@GetMapping("getOneBySchoolID")
	public Object getOneBySchoolID(Integer id) {
		if(id == null) {
			return ResponseUtil.badArgument();
		}
		LitemallSchool school = schoolService.getOneSchool(id);
		return ResponseUtil.ok(school);
	}
}